import {
    JsonController,
    Get,
    Param,
    Post,
    Body,
    NotFoundError,
    HttpCode,
} from "routing-controllers";
import { User, UserModel } from "../entities/User";
import { AppDataSource } from "../database";

@JsonController("/user")
export class UserController {
    private userRepository = AppDataSource.getRepository(User);

    @Get("/:id")
    async getUser(@Param("id") id: number) {
        const user = await this.userRepository.findOneBy({ id });
        if (user) {
            return user;
        } else {
            throw new NotFoundError("user is not found");
        }
    }

    @Get()
    async getUserAll() {
        const [list, total] = await this.userRepository.findAndCount()
        return { list, count: total };
    }


    @Post()
    @HttpCode(201)
    async createUser(@Body() user: UserModel) {
        return this.userRepository.save({ ...user });
    }
}
